package chan.project.smartlawdatamanage.controller;

import chan.project.smartlawcommon.common.BaseResponse;
import chan.project.smartlawcommon.common.ErrorCode;
import chan.project.smartlawcommon.common.ResultUtils;
import chan.project.smartlawcommon.exception.BusinessException;
import chan.project.smartlawdatamanage.service.InstrumentService;
import chan.project.smartlawmodel.dto.instrument.InstrumentAddRequest;
import chan.project.smartlawmodel.entity.Instrument;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.query_dsl.MatchAllQuery;
import co.elastic.clients.elasticsearch._types.query_dsl.Query;
import co.elastic.clients.elasticsearch.core.SearchRequest;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import co.elastic.clients.elasticsearch.indices.DeleteIndexRequest;
import co.elastic.clients.elasticsearch.indices.DeleteIndexResponse;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/data/instrument")
public class InstrumentController {

    @Resource
    private InstrumentService instrumentService;

    @Resource
    private ElasticsearchClient elasticsearchClient;

    /**
     * 添加或更新文书数据
     *
     * @param instrumentAddRequest 文书对象
     * @return 操作结果
     */
    @PostMapping("/add")
    public BaseResponse<Boolean> addInstrument(@RequestBody InstrumentAddRequest instrumentAddRequest) {
        if(ObjectUtil.isEmpty(instrumentAddRequest)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String caseReason = instrumentAddRequest.getCaseReason();
        String caseNumber = instrumentAddRequest.getCaseNumber();
        Date judgmentDate = instrumentAddRequest.getJudgmentDate();
        String title = instrumentAddRequest.getTitle();
        String content = instrumentAddRequest.getContent();
        String court = instrumentAddRequest.getCourt();
        if(StringUtils.isAnyBlank(caseReason, caseNumber, title, content, court)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"参数不能为空");
        }
        if(judgmentDate.after(new Date())){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"文书时间错误");
        }
        Instrument instrument = new Instrument();
        BeanUtils.copyProperties(instrumentAddRequest, instrument);
        boolean save = instrumentService.save(instrument);
        return ResultUtils.success(save);
    }

    /**
     * 根据案号删除文书数据
     *
     * @param InstrumentId id
     * @return 操作结果
     */
    @DeleteMapping("/delete")
    public BaseResponse<Boolean> deleteInstrument(@RequestParam("caseNumber") Long InstrumentId) {
        if (ObjectUtil.isEmpty(InstrumentId)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean b = instrumentService.removeById(InstrumentId);
        if(!b){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"文书已经删除");
        }
        return ResultUtils.success(b);
    }


    /**
     * 获取所有文书数据
     * @return
     */
    @GetMapping("/get")
    private BaseResponse<List<Instrument>> getInstrument() {
        List<Instrument> instruments = new ArrayList<>();
        try {
            // 创建一个MatchAllQuery实例，它将匹配索引中的所有文档
            Query query = new MatchAllQuery.Builder().build()._toQuery();

            // 创建SearchRequest并指定索引名称和查询
            SearchRequest searchRequest = SearchRequest.of(s -> s
                    .index("instrument_index")
                    .query(query)
            );

            // 执行搜索请求
            SearchResponse<Instrument> searchResponse = elasticsearchClient.search(searchRequest, Instrument.class);

            // 获取搜索结果
            instruments = searchResponse.hits().hits().stream()
                    .map(hit -> hit.source())
                    .collect(Collectors.toList());

            // 输出或处理检索到的文档
            for (Instrument instrument : instruments) {
                System.out.println(instrument);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultUtils.success(instruments);
    }

    @DeleteMapping("/deleteAll")
    public BaseResponse<String> deleteAllInstruments() {
        try {
            // 1. 检查索引是否存在
            boolean exists = elasticsearchClient.indices().exists(e -> e.index("instrument_index")).value();
            if (!exists) {
                return ResultUtils.success("索引 'instrument_index' 不存在，无需删除。");
            }
            // 2. 创建 DeleteIndexRequest
            DeleteIndexRequest deleteRequest = DeleteIndexRequest.of(d -> d
                    .index("instrument_index") // 指定要删除的索引名
            );
            // 3. 执行删除操作
            DeleteIndexResponse deleteResponse = elasticsearchClient.indices().delete(deleteRequest);
            // 4. 检查删除结果
            if (deleteResponse.acknowledged()) {
                return ResultUtils.success("索引 'instrument_index' 及其所有数据已成功删除。");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultUtils.error(ErrorCode.SYSTEM_ERROR, "删除索引失败");
    }
}